package com.zzsy.carosshopprojects.activitys.home.mainpage.common;

import android.graphics.Bitmap;
import android.util.Log;

import com.king.base.util.ToastUtils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.base.BaseViewMode;
import com.zzsy.carosshopprojects.util.zxing.activity.CaptureFragment;
import com.zzsy.carosshopprojects.util.zxing.activity.CodeUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

/**
 * 公共的扫码Mode
 */
public class ScanErCodeMode extends BaseViewMode {

    private MutableLiveData<String> liveData;
    private RxAppCompatActivity appCompatActivity;
    public MutableLiveData<String> getLiveData() {
        if (liveData == null)
            liveData = new MutableLiveData<>();
        return liveData;
    }

    /**
     * 加载扫描控件
     */
    public void sanErCode(RxAppCompatActivity appCompatActivity) {
        this.appCompatActivity=appCompatActivity;
        /**
         * 执行扫面Fragment的初始化操作
         */
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);

        captureFragment.setAnalyzeCallback(analyzeCallback);
        /**
         * 替换我们的扫描控件
         */
        appCompatActivity.getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            liveData.postValue(result);
        }

        @Override
        public void onAnalyzeFailed() {
            ToastUtils.showToast(appCompatActivity.getApplicationContext(), appCompatActivity.getApplicationContext().getResources().getString(R.string.erCodeFail));
            appCompatActivity.finish();
        }
    };

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        Log.d("xxxxxa", "销毁了ScanEr");
    }
}
